/**
 * @desc 关系用户对应处理层
 */

import { ErrLogger } from '../middleware/logger';
import ErrorCode, { SuccessCode } from '../utils/errorCode';
import axios from 'axios';
const UserRelationModel = require('../db/userRelation');

// 异常code
const {
  ErrorSaveUserInfo,
  Error500,
} = ErrorCode;

interface UserRelation {
    openid: String, //  必填  用户 openid
    passopenid: String, //  必填  被投票人 passopenid
    time: Number, //  必填  用户投票时间戳 time
    avater: String, //(50)  必填  用户头像
    nickname :String, // (20)  必填  用户微信昵称
}


/**
 * 关系用户登录（投票人）
 */
export const CRelationLogin = (data: any) => {
  return new Promise(async (resolve, reject) => {
    try {
      const { sCode, openid: passopenid } = data
      console.log('sCode', sCode)
      const APPID = "wxe981841c8b4cdb53" 
      const APPSECRET = "9bab5415b9d121040cac7b4fbd0ce9cc"
      // 通过code换取网页授权access_token
      const authorizationRes = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${APPSECRET}&code=${sCode}&grant_type=authorization_code`)
      const { access_token, openid } = authorizationRes.data
      const userinfoRes = await axios.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`)
      const { nickname, headimgurl } = userinfoRes.data
      // 保存用户信息
      CRelationUserSave({openid, nickname, avater: headimgurl, passopenid, time: 1312340000000})
      resolve({
        ...SuccessCode,
        obj: { openid, nickname, headimgurl }
      })
    } catch (err) {
      ErrLogger({
        name: '登录出错',
        err,
      });
      reject(Error500);
    }
  });
}

/**
 * 保存关系用户（投票人）信息
 * @param user 用户类型
 * @returns 
 */
export const CRelationUserSave = (user: UserRelation) => {
  return new Promise(async (resolve, reject) => {
    const { openid, nickname, avater, passopenid, time } = user;
    // 投票信息不全
    if (!openid || !passopenid) {
      reject(ErrorSaveUserInfo);
      return;
    }
    try {
      const vUserModel = new UserRelationModel({
        openid,
        nickname,
        passopenid,
        avater,
        time,
      });
      await vUserModel.save();
      resolve({
        ...SuccessCode,
      });
    } catch (err: any) {
      ErrLogger({
        name: '保存关系用户信息出错',
        err,
      });
      reject(Error500);
    }
  });
}